from django.http import JsonResponse, HttpResponse, HttpResponseNotFound, FileResponse
from django.views.decorators.csrf import csrf_exempt

from login_api.models import User
from user_api.models import Video
from util.fileUtil import VIDEO_IMG_FILE_PATH, VIDEO_FILE_PATH
from util.request_util import post_only, login_only

def _get_username_by_user_id(user_id) -> str:
    try:
        user = User.objects.get(id=user_id)
        return user.username
    except User.DoesNotExist:
        return "账号已注销"

@csrf_exempt
@post_only
def get_last_video_list(request):
    """
    获取最近上传的10个视频
    """
    try:
        # 查询最近上传的10个视频，按照上传时间降序排序
        videos = Video.objects.order_by('-id')[:10]

        video_data = \
            [
                {
                    'title': video.video_title,
                    'desc': video.video_desc,
                    'uuid': video.video_uuid,
                    'time': video.timestamp,
                    'username': _get_username_by_user_id(video.user_id)
                }
                for video in videos
            ]

        # 返回 JSON 响应
        return JsonResponse({'state': 1, 'message': '成功', 'videos': video_data})

    except Exception as e:
        print(e)
        # 处理异常，返回错误信息
        return JsonResponse({'state': -1, 'message': str(e)})


@csrf_exempt
@post_only
def get_video_list_by_user_id(request):
    """
    通过 user_id 获取视频列表
    """
    user_id = request.POST.get("id")

    user = User.objects.filter(id=user_id)
    if not user.first():
        return JsonResponse({'state': -1, 'message': '用户不存在'})

    video_list = Video.objects.filter(user_id=user_id)
    video_data = \
        [
            {
                'title': video.video_title,
                'desc': video.video_desc,
                'uuid': video.video_uuid,
                'time': video.timestamp,
                'username': user[0].username
            }
            for video in video_list
        ]
    return JsonResponse({'state': 1, 'message': '成功', 'videos': video_data})

@csrf_exempt
def get_video_head_img_by_uuid(request, uuid):
    """
    通过视频 uuid 获取视频封面
    """
    img_path = VIDEO_IMG_FILE_PATH / f"{uuid}.png"
    if not img_path.exists():
        return JsonResponse({'state': -1, 'message': '视频封面不存在'})
    with open(img_path, 'rb') as img_file:
        img_data = img_file.read()
    return HttpResponse(img_data, content_type="image/jpeg")

@csrf_exempt
@post_only
def get_video_info_by_uuid(request):
    """
    通过视频 uuid 获取详情信息
    """
    video_uuid = request.POST.get("uuid")
    if not video_uuid:
        return JsonResponse({'state': -1, 'message': '非法请求'})
    try:
        video = Video.objects.get(video_uuid=video_uuid)
    except Video.DoesNotExist:
        return JsonResponse({'state': -1, 'message': '视频不存在'})

    video.view_count += 1
    video.save()

    user_id = video.user_id
    user = User.objects.get(id=user_id)
    username = "用户已注销"
    if user:
        username = user.username

    return JsonResponse({'state': 1, 'video_info': {
                'title': video.video_title,
                'desc': video.video_desc,
                'uuid': video.video_uuid,
                'time': video.timestamp,
                'view_count': video.view_count,
                'love_count': video.love_count,
                'username': username
            }})

@csrf_exempt
def get_stream_video_by_uuid(request, uuid):
    video_path = VIDEO_FILE_PATH / f"{uuid}_merged.mp4"

    if not video_path.exists():
        # 视频文件不存在，可以返回适当的错误响应
        return HttpResponseNotFound("Video not found")

    response = FileResponse(open(video_path, 'rb'), content_type='video/mp4')
    return response
